package cn.zzuli.activemq.demo.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

public class JmsConsumer1 {
    private static final String ACTIVEMQ_URL = "tcp://81.70.205.143:61617";

    private static final String QUEUE_NAME = "queue_01";

    public static void main(String[] args) throws JMSException, IOException {
        System.out.println("1  *****");
        //1.创建链接工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);

        //2.通过连接工厂获得获得链接connection,并启动访问
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();


        //3.创建会话session
        //3.1第一个参数 事务，第二个参数 签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //4.创建目的地，此处使用队列
        Queue queue = session.createQueue(QUEUE_NAME);

        //5.创建消息消费者
        MessageConsumer consumer = session.createConsumer(queue);

        /**
            同步阻塞方式
             while (true) {
             TextMessage message = (TextMessage) produce.receive();
             if (message != null) {
             System.out.println(message.getText() + "      《******消息体");
             } else {
             break;
             }
             }
             produce.close();
             session.close();
             connection.close();
         */

        //通过监听的方式来消费消息

        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                if (message != null && message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    try {
                        System.out.println("********使用listener"+textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.in.read();
        consumer.close();
        session.close();
        connection.close();
    }
}
